package com.project.common.data.mybatis.provider.utils;

import com.project.common.data.mybatis.metadata.TableColumn;

import java.lang.reflect.Field;

public class ProviderUtils {

    public static String buildParameter(TableColumn tableColumn) {
        return String.join("", "#{", tableColumn.getProperty(), "}");
    }

    public static String buildAssignment(TableColumn tableColumn) {
        return tableColumn.getName() + " = " + buildParameter(tableColumn);
    }

    public static String buildDmAssignment(TableColumn tableColumn) {
        return "\"" + tableColumn.getName() + "\" = " + buildParameter(tableColumn);
    }


    public static boolean checkField(TableColumn tableColumn, Class<?> entityClass, Object target) {
        if (target == null) {
            return false;
        }
        if (tableColumn.isUpdateToNull()) {
            return true;
        }
        try {
            Field field = entityClass.getDeclaredField(tableColumn.getProperty());
            if (field != null) {
                field.setAccessible(true);
                Object value = field.get(target);
                // 如果对象为空，则返回
                return value != null;
            }
            return false;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            return false;
        }
    }
}
